<?php
if ( !defined('IMAGEHOLDER') )
define('IMAGEHOLDER',get_bloginfo('template_url').'/images/placeholder.png');



add_filter( 'template_include', 'building_page_template', 99 );
function building_page_template( $template ) {
global $post;
	if ( is_single() && get_post_type( $post->ID ) == 'building' ) {
		$new_template = locate_template( array( 'inc/building/templates/single-building.php' ) );
		if ( '' != $new_template ) {
			return $new_template ;
		}
	}
	if(is_archive() && get_post_type( $post->ID ) == 'building'){
		$new_template = locate_template( array( 'inc/building/templates/archive-building.php' ) );
		if ( '' != $new_template ) {
			return $new_template ;
		}	}		
	return $template;
}

//
add_shortcode( 'building_featured', 'building_featured' );
function building_featured( $atts ,$content = null){
	global $post , $wp_query;
	if ( empty( $atts ) ) return;

	extract( shortcode_atts( array(
		'per_page' 		=> '12',
		'columns' 		=> '3',
		'orderby'   	=> 'title',
		'order'     	=> 'desc'		
		), $atts ) );
		
	$meta_query  = 	array(
			'key' => 'building_is_featured',
			'value' => '1'
	);
	
	$args = array(
		'post_type'		=> 'building',
		'post_status'	=> 'publish',
		'ignore_sticky_posts'	=> 1,		
		'posts_per_page'=> $per_page,
		'orderby'		=> $orderby,
		'order' 		=> $order,
		'meta_query'	=> $meta_query		
	);
	ob_start();
	$wp_query = new WP_Query( $args );
	
	if ( $wp_query->have_posts() ) : $i=0;?>	
		<?php echo '<ul class="item-grid">';?>
			<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>		
			<?php
				echo ($i!=0 && $i%$columns==0) ? '</ul><ul class="item-grid">' : '';
			?>
				<?php get_template_part( 'inc/building/loop/content', 'building' ); ?>
				<?php $i++;?>
			<?php endwhile;?>
		<?php echo '</ul>';?>
	<?php endif;
	wp_reset_postdata();
	$content = ob_get_contents();
	ob_end_clean();
	return $content;
}
add_shortcode( 'building_category', 'building_category' );
function building_category( $atts ,$content = null){
	global $post , $wp_query;
	if ( empty( $atts ) ) return;
	$taxonomy = 'building-type';
	extract( shortcode_atts( array(
		'per_page' 		=> '12',
		'columns' 		=> '3',
		'orderby'   	=> 'title',
		'order'     	=> 'desc',
		'category'		=> ''
		), $atts ) );
	if ( ! $category ) return;	
	$term = get_term( $category, $taxonomy );
	
	if(! $term )  return;	
	$args = array(
		'post_type'		=> 'building',
		'post_status'	=> 'publish',
		'ignore_sticky_posts'	=> 1,
		'posts_per_page'=> $per_page,
		'orderby'		=> $orderby,
		'order' 		=> $order,
		'tax_query' 	=> array(
		    	array(
			    	'taxonomy' => $taxonomy,		
					'terms' 		=> array( esc_attr($term->slug) ),
					'field' 		=> 'slug',
					'operator' 		=> 'IN'
				)
		    )
	);
	ob_start();
	$wp_query = new WP_Query( $args );	
	if ( $wp_query->have_posts() ) : $i=0;?>	
		<?php echo '<ul class="item-grid">';?>
			<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>		
			<?php
				echo ($i!=0 && $i%$columns==0) ? '</ul><ul class="item-grid">' : '';
			?>
				<?php get_template_part( 'inc/building/loop/content', 'building' ); ?>
				<?php $i++;?>
			<?php endwhile;?>
		<?php echo '</ul>';?>
	<?php else:?>	
		<?php get_template_part( 'inc/building/loop/empty', 'index' ); ?>	
	<?php endif;
	wp_reset_postdata();
	$content = ob_get_contents();
	ob_end_clean();
	return '<ul class="item-grid">'.$content.'</ul>' ;
}
add_shortcode( 'building_categories', 'building_categories' );
function building_categories( $atts ) {
	global $post , $wp_query;
	if ( empty( $atts ) ) return;
	$taxonomy = 'building-type';
	extract( shortcode_atts( array(
		'per_page' 		=> '-1',
		'columns' 		=> '3',
		'orderby'   	=> 'title',
		'order'     	=> 'desc',
		'ids'			=> ''
		), $atts ) );
	if ( ! $ids ) return;	
	$array_term_id = array();
	$array_term_id_tmp = array();
	$ids = explode(',',$ids);
	foreach($ids as $id){
		$array_term_id[] = $id;
	}
	if(empty($array_term_id)) return;
	$categories = get_terms( $taxonomy, array('hide_empty'=>false));	
	if(! $categories )  return;
	foreach($categories as $cat ){
		$array_term_id_tmp[] = $cat-> term_id;
	}
	$arrayID = array_intersect($array_term_id , $array_term_id_tmp);
	if(empty($arrayID)) return;
	
	$arraySlug = array();
		foreach($arrayID as $id){
			$term = get_term($id,$taxonomy);
			$arraySlug[] = $term->slug;
		}	
	$args = array(
		'post__not_in'	=> array($atts['exclude']),
		'post_type'		=> 'building',
		'post_status'	=> 'publish',
		'ignore_sticky_posts'	=> 1,
		'posts_per_page'=> $per_page,
		'orderby'		=> $orderby,
		'order' 		=> $order,
		'tax_query' 	=> array(
		    	array(
			    	'taxonomy' 		=> $taxonomy,		
					'terms' 		=> $arraySlug,
					'field' 		=> 'slug',
					'operator' 		=> 'IN'
				)
		    )
	);	
	ob_start();
	$wp_query = new WP_Query( $args );	
	if ( $wp_query->have_posts() ) : $i=0;?>	
		<?php echo '<ul class="item-grid">';?>
			<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>		
			<?php
				echo ($i!=0 && $i%3==0) ? '</ul><ul class="item-grid">' : '';
			?>
				<?php get_template_part( 'inc/building/loop/content', 'building' ); ?>
				<?php $i++;?>
			<?php endwhile;?>
		<?php echo '</ul>';?>	
	<?php endif;
	wp_reset_postdata();
	$content = ob_get_contents();
	ob_end_clean();
	return '<ul class="item-grid">'.$content.'</ul>' ;
}

add_action('wp_footer','add_script_orderby');
function add_script_orderby(){
	if(isset($_GET['orderby'])){
		if( $_GET['orderby'] == 'title' || $_GET['orderby'] == 'date' || $_GET['orderby'] == 'modified' || $_GET['orderby'] == 'price'){
			if(!isset($_GET['order'])){			
				$id = '#j_orderby_'.$_GET['orderby'];
				$value = '?orderby='.$_GET['orderby'].'&order=ASC';
				echo '
					<script type="text/javascript">
						jQuery(document).ready(function(){
							jQuery("'.$id.'").attr("href","'.$value.'");
						})
					</script>
				';
			}
		}
	}
	if(isset($_GET['s'])){
		$id = 'j_orderby_'.$_GET['orderby'];
		$value = '?orderby='.$_GET['orderby'].'&order=ASC';
		echo '
		<script type="text/javascript">
			jQuery(document).ready(function(){
				var url = window.location.search;
				url = url.replace("&order=ASC","");
				url = url.replace("&orderby=title","");
				url = url.replace("&orderby=date","");
				url = url.replace("&orderby=modified","");
				url = url.replace("&orderby=price","");
				jQuery(".archive.search .col-main > .toolbar a.order-link").each(function(){
					var url_this = jQuery(this).attr("href");
					jQuery(this).attr("href",url+url_this.replace("?","&"));					
				})				
			})
		</script>
		';
	}
}

add_action('toolbar_order','toolbar_order');
function toolbar_order(){
	$output = '<div class="toolbar">';
	$output .= '<span class="order-text">'. __('Order by:' , 'building' ) .'</span>';	
	$output .= '<a class="order-link" id="j_orderby_title" href="?orderby=title">'. __('Name' , 'building' ) .'</a>';
	$output .= '<a class="order-link" id="j_orderby_date" href="?orderby=date">'. __('Created' , 'building' ) .'</a>';
	$output .= '<a class="order-link" id="j_orderby_modified" href="?orderby=modified">'. __('Modified' , 'building' ) .'</a>';
	$output .= '<a class="order-link" id="j_orderby_price" href="?orderby=price">'. __('Price' , 'building' ) .'</a>';
	$output .= '</div>';
	echo $output;
}

add_action('get_order','set_get_order');
function set_get_order(){		
	$order = 'DESC';
	$orderby = 'title';
	$arr_order = array();
	if(isset($_REQUEST['orderby'])){		
		if( $_REQUEST['orderby'] == 'price' ){
			$orderby = 'price';				
			if(isset($_REQUEST['order'])){	$order = 'ASC'; }
				$arr_order =array( 'orderby' => 'meta_value_num' ,'meta_key' => 'building_cost' , 'order'	=> $order );
		}else{
			if(isset($_REQUEST['order'])){	$order = 'ASC'; }
			if( $_REQUEST['orderby'] == 'title' || $_REQUEST['orderby'] == 'date' || $_REQUEST['orderby'] == 'modified'){
				$orderby = $_REQUEST['orderby'];
			}
			$arr_order = array( 'order'	=> $order , 'orderby' => $orderby);
		}
	}else{
		$arr_order = array( 'order'	=> $order , 'orderby' => $orderby);
	}	
	return $arr_order;
}

function GetListImage($postID,$metakey){
	global $wpdb;
	$list_image = '';
    $images = get_post_meta( $postID, $metakey, false );
    $images = implode( ',' , $images );	
    $images = $wpdb->get_col( " SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND ID in ({$images}) ORDER BY menu_order ASC  " );	
    foreach ( $images as $key => $att ) {		
		$url_image_thumb = wp_get_attachment_image_src( $att, 'thumbnail' );
        $url_image_full  = wp_get_attachment_image_src( $att, 'full' );		
        $list_image .= '<a href="'.$url_image_full[0].'"><img src="'.$url_image_full[0].'" data-thumb="'.$url_image_thumb[0].'"/></a>';
    }	
	return $list_image;
}
function getImagesPost($postID,$metakey,$icon){
	global $wpdb;
	$arrayImages = array();
    $images = get_post_meta( $postID, $metakey, false );
    $images = implode( ',' , $images );	
    $images = $wpdb->get_col( " SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND ID in ({$images}) ORDER BY menu_order ASC  " );	
    foreach ( $images as $att ) {
		$arrayImages[] = wp_get_attachment_image_src( $att, $icon );
    }
	return $arrayImages;
}
function returnImageFirst($post){	
	$arr_images = getImagesPost($post->ID,'building_imgadv','thumbnail');
	if(has_post_thumbnail($post->ID)){
		the_post_thumbnail('thumbnail');
	}else if( count($arr_images) > 0 ){
		echo '<img src="'.$arr_images[0][0].'" alt="'.get_the_title($post->ID).'"/>';
	}else{
		echo '<img src="'.IMAGEHOLDER.'" alt="'.get_the_title($post->ID).'"/>';
	}
}
function j_get_author() {
if(ICL_LANGUAGE_CODE == 'vi'){
	$action_url = get_bloginfo('url').'building/';
}else{
	$action_url = get_bloginfo('url').'/building/';
}
	printf( __( '%1$s', 'building' ),		
		sprintf( '<a href="%1$s" title="%2$s">%3$s</a>',
			//get_author_posts_url( get_the_author_meta( 'ID' ) ),
			$action_url.'?s=+&author='.get_the_author_meta('ID'),
			sprintf( esc_attr__( 'View all posts by %s', 'twentyten' ), get_the_author() ),
			get_the_author()
		)
	);
}
function getAllMetakeyBuilding($meta_key){
	global $wpdb;
	$lg = ICL_LANGUAGE_CODE ;
	$location = array();
	$location_tmp = array();	
	$sql = "
		SELECT meta_value
		FROM wp_postmeta
		LEFT JOIN wp_icl_translations ON wp_postmeta.post_id = wp_icl_translations.element_id
		WHERE wp_icl_translations.language_code = '{$lg}'
		AND wp_postmeta.meta_key = '{$meta_key}'
	";
    $arr_location = $wpdb->get_col( $sql );	
    foreach ( $arr_location as $loc ) {		
		if($loc != '' || $loc != null){
			$tmp = str_replace(' ','',strtolower($loc));
			if(!in_array($tmp,$location_tmp)){
				$location_tmp[] = $tmp;
				$location[] = $loc;
			}		
		}
    }	
	return $location;
}
function getLocation(){
	return getAllMetakeyBuilding('building_district');	
}
function getBedRoom(){
	return getAllMetakeyBuilding('building_num_bedroom');
}
function my_search_form( $form ) {
	ob_start();
	get_template_part('/inc/building/formsearch');
	$form = ob_get_contents();
	ob_end_clean();
    return $form;
}
add_filter( 'get_search_form', 'my_search_form' );
function __search_by_title_only( $search, &$wp_query ){
    global $wpdb;
    if ( empty( $search ) )
        return $search;
    $q = $wp_query->query_vars;
    $n = ! empty( $q['exact'] ) ? '' : '%';
    $search =
    $searchand = '';
    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }
    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }
    return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );
function search_building( $query ) {
	if($_GET['s'] == '')
		$query->set('s', ' ' );	
    if ( !is_admin() && is_search() && $query->is_main_query()){
		$query->set('post_type', 'building' );	
		$taxonomy = 'building-type';
		$meta_query = array();
		$tax_query = array();
		if(isset($_GET['term_id'])){
			if(!empty($_GET['term_id']) &&  $_GET['term_id'] != null){
				$terms = $_GET['term_id'];
				$tax_query[] =  array(
					'taxonomy' 	=> $taxonomy,
					'field'		=> 'id',
					'terms' 	=> $terms,
					'operator' 	=> 'IN'
				);		
			}
			$query->set('tax_query', $tax_query );
		}	
		if(isset($_GET['type']) && !empty($_GET['type']) &&  $_GET['type'] != null ){
			$meta_query[] = array(
				'key'		=> 'building_type',
				'value' 	=> $_GET['type'],
				'compare' 	=> 'IN'
			);
		}
		if(isset($_GET['location']) && !empty($_GET['location']) &&  $_GET['location'] != null ){
			$meta_query[] = array(
				'key'		=> 'building_district',
				'value' 	=> array($_GET['location']),
				'compare' 	=> 'IN'
			);
		}
		if(isset($_GET['bedroom']) && !empty($_GET['bedroom']) &&  $_GET['bedroom'] != null ){
			$meta_query[] = array(
				'key'		=> 'building_num_bedroom',
				'value' 	=> array($_GET['bedroom']),
				'compare' 	=> 'IN'
			);
		}
		
		$query->set('meta_query', $meta_query );
		$query->set('post_type', 'building' );
	}		
}
add_action( 'pre_get_posts', 'search_building', 1 );

add_action('init','InsertImageBuildingConsignment');
function InsertImageBuildingConsignment(){
	if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
		if( $_POST["action"] == "uploadImage" ){
			require_once(ABSPATH . "wp-admin" . '/includes/image.php');
			require_once(ABSPATH . "wp-admin" . '/includes/file.php');
			require_once(ABSPATH . "wp-admin" . '/includes/media.php');
			$output = '';
			if(isset($_FILES['photoimg1']) and $_FILES['photoimg1']['name'] != null and $_FILES['photoimg1']['name'] != ''){
				$attach_id = media_handle_upload('photoimg1',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}		
			if(isset($_FILES['photoimg2']) and $_FILES['photoimg2']['name'] != null and $_FILES['photoimg2']['name'] != ''){
				$attach_id = media_handle_upload('photoimg2',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}	
			if(isset($_FILES['photoimg3']) and $_FILES['photoimg3']['name'] != null and $_FILES['photoimg3']['name'] != ''){
				$attach_id = media_handle_upload('photoimg3',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}	
			if(isset($_FILES['photoimg4']) and $_FILES['photoimg4']['name'] != null and $_FILES['photoimg4']['name'] != ''){
				$attach_id = media_handle_upload('photoimg4',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}	
			if(isset($_FILES['photoimg5']) and $_FILES['photoimg5']['name'] != null and $_FILES['photoimg5']['name'] != ''){
				$attach_id = media_handle_upload('photoimg5',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}	
			if(isset($_FILES['photoimg6']) and $_FILES['photoimg6']['name'] != null and $_FILES['photoimg6']['name'] != ''){
				$attach_id = media_handle_upload('photoimg6',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}	
			if(isset($_FILES['photoimg7']) and $_FILES['photoimg7']['name'] != null and $_FILES['photoimg7']['name'] != ''){
				$attach_id = media_handle_upload('photoimg7',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}	
			if(isset($_FILES['photoimg8']) and $_FILES['photoimg8']['name'] != null and $_FILES['photoimg8']['name'] != ''){
				$attach_id = media_handle_upload('photoimg8',0);									
				$output .= '<input type="hidden" value="'.$attach_id.'" name="building_img[]"/>';				
			}
			$output .= '<script>$(document).ready(function(){$("input[name=action]").attr("value","consignment");$("#register_building").submit();})</script>';
			echo $output;
		}elseif($_POST["action"] == "consignment"){
			$messege = '';
			if(isset($_POST['building_img']) && $_POST['building_img'] != null){
				$user = wp_get_current_user();
				if(empty($user->data)){
					$author = 1;
				}else{
					$author = $user->ID;
				}
				$my_post = array(
				  'post_title'    => wp_strip_all_tags( $_POST['post_title'] ),
				  'post_status'   => 'pending', 
				  'post_type'     => 'building',
				  'post_content'  => $_POST['building_content'],
				  'post_author'   => $author  
				);
				$post_id = wp_insert_post( $my_post );	
				$pageid = 58 ;if(ICL_LANGUAGE_CODE == 'vi') $pageid = 76 ;
				if($post_id){
					add_post_meta($post_id,'building_address',wp_strip_all_tags( $_POST['building_address'] ));
					add_post_meta($post_id,'building_district',wp_strip_all_tags( $_POST['building_district'] ));
					add_post_meta($post_id,'building_street',wp_strip_all_tags( $_POST['building_street'] ));
					add_post_meta($post_id,'building_allow_test',wp_strip_all_tags( $_POST['building_allow_test'] ));
					add_post_meta($post_id,'building_cost',wp_strip_all_tags( $_POST['building_cost'] ));
					add_post_meta($post_id,'building_currency',wp_strip_all_tags( $_POST['building_currency'] ));
					add_post_meta($post_id,'building_extra_infomation',wp_strip_all_tags( $_POST['building_extra_infomation'] ));
					add_post_meta($post_id,'building_interior',wp_strip_all_tags( $_POST['building_interior'] ));
					add_post_meta($post_id,'building_land_area',wp_strip_all_tags( $_POST['building_land_area'] ));
					add_post_meta($post_id,'building_usable_area',wp_strip_all_tags( $_POST['building_usable_area'] ));
					add_post_meta($post_id,'building_num_bedroom',wp_strip_all_tags( $_POST['building_num_bedroom'] ));
					add_post_meta($post_id,'building_type',wp_strip_all_tags( $_POST['post_type_search']));
					foreach( $_POST['building_img'] as $item ){
						add_post_meta($post_id,'building_imgadv', $item);
					}						
					$location = get_page_link($pageid) .'?statusMessage="ok"';
					wp_redirect( $location ); exit();
				}else{										
					$location = get_page_link($pageid) .'?statusMessage="error';
					wp_redirect( $location ); exit();
				}	
			}
			echo $messege;				
		}
	}		
}
function my_new_contactmethods( $contactmethods ) {
$contactmethods['twitter'] = 'Twitter';
$contactmethods['facebook'] = 'Facebook';
$contactmethods['company'] = 'Company'; 
$contactmethods['mobile'] = 'Mobile'; 
$contactmethods['image'] = 'image'; 
return $contactmethods;
}
add_filter('user_contactmethods','my_new_contactmethods',10,1);

function count_user_posts_by_type( $userid, $post_type = 'post' ) {
	global $wpdb;
	$where = get_posts_by_author_sql( $post_type, true, $userid );
	$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  	return apply_filters( 'get_usernumposts', $count, $userid );
}
?>